<template>
    <view class="container">
        <view class="header">
            <image class="avatar" src="/static/images/avatar.png"></image>
            <navigator url="#" class="nav" hover-class="none" v-if="user?.phone">
                <view class="name">{{user?.name}}{{groupText(user.group)}}</view>
                <view class="name">{{user?.phone?.replace(/(\d{3})\d{4}(\d{4})$/, '$1****$2')}}</view>
                <view class="store">八桂客配送系统</view>
            </navigator>
            <navigator url="/pages/login/login" class="nav" hover-class="none" v-else>
                <view class="name">登 录</view>
            </navigator>
        </view>
        <view>
            <view class="menu">
                <view @click.stop="hdClose" class="item" v-if="user?.phone">
                    <view class="title">
                        <uni-icons type="close" color="#f37b1d"></uni-icons>
                        <view class="text">注销账号</view>
                    </view>
                    <uni-icons type="forward"></uni-icons>
                </view>
                <view class="item" @click="readPolicy('privacy')">
                    <view class="title">
                        <uni-icons type="eye" color="#f37b1d"></uni-icons>
                        <text class="text">隐私政策</text>
                    </view>
                    <uni-icons type="forward"></uni-icons>
                </view>
                <view class="item" @click="readPolicy('agreement')">
                    <view class="title">
                        <uni-icons type="locked" color="#f37b1d"></uni-icons>
                        <text class="text">用户协议</text>
                    </view>
                    <uni-icons type="forward"></uni-icons>
                </view>
                <view @click.stop="chkVersion" class="item">
                    <view class="title">
                        <uni-icons type="info" color="#f09853" />
                        <view class="text">版本{{global.version||'0.0.0'}}</view>
                    </view>
                    <uni-icons type="forward"></uni-icons>
                </view>
            </view>
        </view>
        <view>
            <view class="logout" v-if="user?.phone" @click="hdLogout">退出登录</view>
        </view>
    </view>
    <bgk-upgrade-dialog :desc="global.upgrade.desc" ref="upgradeRef" @upgrade="hdUpgrade"></bgk-upgrade-dialog>
</template>

<script lang="ts" setup>
    import { ref, computed } from 'vue'
    import { onLoad, onShow, onPullDownRefresh } from '@dcloudio/uni-app'
    import { useGlobalStore } from '@/stores/global'
    import { logout, userClose } from './service'
    import Constants from '@/utils/constants'
    import { downloadApp } from '@/utils/upgrade'
    import Func from '@/utils/functions'
    import Settings from '@/config/settings'
    import LocalStorage from '@/utils/localstorage'

    const global = useGlobalStore()
    const upgradeRef = ref()
    const user = computed(() => {
        return global.user
    })

    const groupText = value => {
        const map = {
            [Constants.DELIVERYER_GROUP_BOY]: '男生',
            [Constants.DELIVERYER_GROUP_GIRL]: '女生',
        }
        const text = map[value] || ''
        return text ? `(${text})` : ''
    }
    
    const hdUpgrade = () => {
        try {
            if (plus.os.name.toLowerCase() == 'ios') {
                plus.runtime.openURL('itms-apps://apps.apple.com/cn/app/id6504438044?mt=8', e => {
                    Func.showToast({ title: '应用无法更新' })
                })
            } else {
                downloadApp(global.upgrade.url, global.upgrade.type)
            }
        } catch (e) {
            console.log(e)
        } finally {
        }
    }

    const chkVersion = async () => {
        try {
            Func.showLoading()
            const check = () => {
                return new Promise((resolve, reject) => {
                    //判断App版本
                    uni.$emit('checkVersionUpgradeEvent', () => {
                        if (Func.versionCompare(global.upgrade.ver, global.version) === 1) {
                            upgradeRef.value.open()
                        } else {
                            Func.showToast({ title: '该版本已是最新版' })
                        }
                        resolve(true)
                    })
                })

            }
            await check()
        } catch (e) {
            console.log(e)
        } finally {
            Func.hideLoading()
        }
    }

    const onrefresh = async () => {
        try {
            const chkUser = () => {
                return new Promise((resolve, reject) => {
                    uni.$emit('refreshUserEvent', () => {
                        resolve(true)
                        if (!user.value?.id) {
                            Func.redirectTo({
                                url: Settings.loginPath
                            })
                        }
                    })
                })
            }
            await chkUser()
        } catch (e) {
            console.log(e)
        } finally {
        }
    }

    onPullDownRefresh(async () => {
        await onrefresh()
        uni.stopPullDownRefresh()
    })

    const readPolicy = type => {
        let v = ''
        if (type == 'agreement') {
            v = JSON.stringify(Settings.agreement)
        } else if (type == 'privacy') {
            v = JSON.stringify(Settings.privacy)
        }
        Func.navigateTo({
            url: '/pages/policy?v=' + v
        })
    }

    const hdClose = async () => {
        try {
            const modal = await Func.showModal({
                content: '注销账号后将不可恢复，确定要注销账号?'
            }, true)
            if (modal?.confirm === true) {
                const res = await userClose()
                if (res?.code === Constants.API_SUCCESS) {
                    global.setUser()
                    return Func.redirectTo({
                        url: Settings.loginPath
                    })
                }
                throw res
            }
        } catch (e) {
            console.log(e)
            e?.code == Constants.CLIENT_ERROR && (e.text = e.msg)
            Func.hdError(e, '注销失败')
        }
    }

    const hdLogout = async () => {
        try {
            const modal = await Func.showModal({
                content: '确定要退出登录吗？'
            }, true)
            if (modal?.confirm === true) {
                Func.showLoading()
                const res = await logout()
                if (res?.code === Constants.API_SUCCESS) {
                    global.setUser()
                    LocalStorage.clear()
                    Func.showToast({ title: '已退出登录' })
                    await Func.sleep()
                    return Func.redirectTo({
                        url: Settings.loginPath
                    })
                }
                throw res
            }
        } catch (e) {
            console.log(e)
            e?.code == Constants.CLIENT_ERROR && (e.text = e.msg)
            Func.hdError(e, Func.t('The operation failed'))
        } finally {
            Func.hideLoading()
        }
    }
    onShow(() => {
        onrefresh()
    })
    onLoad(async () => {
        const version = await Func.getVersion()
        version?.ver && (global.version = version.ver)
    })
</script>

<style lang="scss" scoped>
    @mixin font($size: 28rpx, $color: #000000, $family: 'Helvetica Neue, Helvetica, sans-serif', $weight: 400) {
        /* height: $size !important; */
        /* line-height: $size !important; */
        font-family: $family !important;
        font-size: $size !important;
        color: $color !important;
        font-weight: $weight !important;
    }

    @each $n in 1 {
        .flex-#{$n} {
            flex: #{$n};
        }
    }

    .container {
        & .header {
            display: flex;
            align-items: center;
            background-color: #ffffff;
            padding: 30rpx;
            margin-top: 10rpx;

            & .avatar {
                display: block;
                width: 128rpx;
                height: 128rpx;
            }

            & .nav {
                padding: 10rpx;

                & .name {
                    @include font(32rpx, #333333, 'Helvetica Neue, Helvetica, sans-serif', bold);
                }

                & .store {
                    font-size: 28rpx;
                    margin-top: 10rpx;
                }
            }
        }

        & .menu {
            margin-top: 20rpx;
            background-color: #ffffff;
            font-size: 28rpx;

            & .item {
                display: flex;
                flex-direction: row;
                justify-content: space-between;
                align-items: center;
                padding: 25rpx 30rpx;
                border-bottom: 2rpx solid #e5e5e5;

                & .title {
                    display: flex;
                    align-items: center;

                    & .text {
                        margin-left: 10rpx;
                    }

                    & .icon {
                        width: 32rpx;
                        height: 32rpx;
                    }
                }
            }
        }

        & .logout {
            background-color: #00AAEE;
            color: #fff;
            margin: 30rpx 0rpx;
            padding: 30rpx 0;
            text-align: center;
        }
    }
</style>